package com.zx.callback.service.impl;

import com.zx.callback.common.enums.MessageEnumTable;
import com.zx.callback.common.enums.UsedScopeEnum;
import com.zx.callback.common.enums.UsedStateEnum;
import com.zx.callback.common.ex.JsonResponseException;
import com.zx.callback.common.utils.DateUtil;
import com.zx.callback.dao.CouponInfoMapper;
import com.zx.callback.po.CouponInfo;
import com.zx.callback.service.CouponInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 *
 * 优惠卷服务
 * @author ：yanst
 * @since: 2017/11/24
 * @history：(date editor desc)
 */
@Service
public class CouponInfoServiceImpl extends BaseService implements CouponInfoService {

    @Resource
    private CouponInfoMapper couponInfoMapper;


    @Override
    public CouponInfo detail(Long id) {
        return couponInfoMapper.selectByPrimaryKey(id);
    }

    /**
     * 验证优惠卷是否可以用(购票)
     * @param couponId
     * @return
     */
    @Override
    public BigDecimal validCouponIsUse(Long couponId){
        CouponInfo couponInfo = couponInfoMapper.selectByPrimaryKey(couponId);
        if (couponInfo == null
                || couponInfo.getUsedState() == null
                || couponInfo.getExpiry() == null
                || couponInfo.getUsedScope() == null){
            logger.error("优惠卷不存在，couponId={}", couponId);
            throw new JsonResponseException(MessageEnumTable.COUPON_NOT_EXIST);
        }

        if(UsedStateEnum.ALREADY_USED.getKey().byteValue() == couponInfo.getUsedState()){
            logger.error("优惠卷已经使用，couponId={}", couponId);
            throw new JsonResponseException(MessageEnumTable.COUPON_ALREADY_USE);
        }

        if(!(UsedScopeEnum.ALL_PLATFORM.getKey().byteValue() == couponInfo.getUsedState()
                ||UsedScopeEnum.BUY_TICKET.getKey().byteValue() == couponInfo.getUsedState())){
            logger.error("该优惠卷不能用于支付购票票款，couponId={}", couponId);
            throw new JsonResponseException(MessageEnumTable.COUPON_NOT_SUPPORT);
        }

        if(DateUtil.comparisonDate1(new Date(),couponInfo.getExpiry())){
            logger.error("优惠卷已经过期，couponId={}", couponId);
            throw new JsonResponseException(MessageEnumTable.COUPON_ALREDY_EXPIRY);
        }
        return couponInfo.getAmount();

    }

    @Override
    public void userCoupon(Long couponId) {
        CouponInfo couponInfo = new CouponInfo();
        couponInfo.setId(couponId);
        couponInfo.setUsedState(UsedStateEnum.ALREADY_USED.getKey());
        couponInfoMapper.updateByPrimaryKeySelective(couponInfo);
    }

}
